// DOM 元素
const totalClicksEl = document.getElementById('totalClicks');
const dailyClicksEl = document.getElementById('dailyClicks');
const displayedClicksEl = document.getElementById('displayedClicks');
const historyTableBody = document.getElementById('historyTableBody');
const searchInput = document.getElementById('searchInput');
const searchBtn = document.getElementById('searchBtn');
const clearSearchBtn = document.getElementById('clearSearchBtn');
const pageInfo = document.getElementById('pageInfo');
const prevPageBtn = document.getElementById('prevPageBtn');
const nextPageBtn = document.getElementById('nextPageBtn');
const pageInput = document.getElementById('pageInput');
const totalPagesSpan = document.getElementById('totalPagesSpan');
const goPageBtn = document.getElementById('goPageBtn');

// 过滤按钮
const filterAllBtn = document.getElementById('filterAll');
const filterTodayBtn = document.getElementById('filterToday');
const filterYesterdayBtn = document.getElementById('filterYesterday');
const filterWeekBtn = document.getElementById('filterWeek');

// 导出按钮
const exportJsonBtn = document.getElementById('exportJsonBtn');
const exportCsvBtn = document.getElementById('exportCsvBtn');
const refreshBtn = document.getElementById('refreshBtn');
const clearAllBtn = document.getElementById('clearAllBtn');

// 全局变量
let allClicks = [];
let filteredClicks = [];
let currentPage = 1;
const pageSize = 50;
let currentFilter = 'all';
let searchQuery = '';

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    loadData();
    bindEvents();
});

// 绑定事件
function bindEvents() {
    // 搜索功能
    searchBtn.addEventListener('click', handleSearch);
    clearSearchBtn.addEventListener('click', clearSearch);
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            handleSearch();
        }
    });

    // 过滤功能
    filterAllBtn.addEventListener('click', () => setFilter('all'));
    filterTodayBtn.addEventListener('click', () => setFilter('today'));
    filterYesterdayBtn.addEventListener('click', () => setFilter('yesterday'));
    filterWeekBtn.addEventListener('click', () => setFilter('week'));

    // 分页功能
    prevPageBtn.addEventListener('click', () => changePage(currentPage - 1));
    nextPageBtn.addEventListener('click', () => changePage(currentPage + 1));
    goPageBtn.addEventListener('click', () => {
        const page = parseInt(pageInput.value);
        if (page && page > 0) {
            changePage(page);
        }
    });

    // 页码输入框回车事件
    pageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            const page = parseInt(pageInput.value);
            if (page && page > 0) {
                changePage(page);
            }
        }
    });

    // 导出功能
    exportJsonBtn.addEventListener('click', exportToJson);
    exportCsvBtn.addEventListener('click', exportToCsv);
    refreshBtn.addEventListener('click', loadData);
    clearAllBtn.addEventListener('click', clearAllData);
}

// 加载数据
async function loadData() {
    try {
        showLoading();
        const data = await chrome.storage.local.get(['clickHistory', 'totalClicks', 'dailyClicks']);

        allClicks = data.clickHistory || [];
        updateStats(data.totalClicks || 0, data.dailyClicks || 0);
        applyFilters();

    } catch (error) {
        console.error('Failed to load data:', error);
        showError('Failed to load data');
    }
}

// 显示加载状态
function showLoading() {
    historyTableBody.innerHTML = '<tr><td colspan="6" class="loading">Loading...</td></tr>';
}

// 更新统计信息
function updateStats(totalClicks, dailyClicks) {
    totalClicksEl.textContent = formatNumber(totalClicks);
    dailyClicksEl.textContent = formatNumber(dailyClicks);
}

// 设置过滤器
function setFilter(filter) {
    currentFilter = filter;
    currentPage = 1;

    // 更新按钮状态
    document.querySelectorAll('.filter-buttons .btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.getElementById(`filter${filter.charAt(0).toUpperCase() + filter.slice(1)}`).classList.add('active');

    applyFilters();
}

// 应用过滤器
function applyFilters() {
    let filtered = [...allClicks];

    // 时间过滤
    if (currentFilter !== 'all') {
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
        const weekStart = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);

        filtered = filtered.filter(click => {
            const clickTime = new Date(click.timestamp);

            switch (currentFilter) {
                case 'today':
                    return clickTime >= today;
                case 'yesterday':
                    return clickTime >= yesterday && clickTime < today;
                case 'week':
                    return clickTime >= weekStart;
                default:
                    return true;
            }
        });
    }

    // 搜索过滤
    if (searchQuery) {
        const query = searchQuery.toLowerCase();
        filtered = filtered.filter(click => {
            try {
                const domain = new URL(click.url).hostname.toLowerCase();
                const element = click.element.selector.toLowerCase();
                const text = (click.element.text || '').toLowerCase();

                return domain.includes(query) ||
                    element.includes(query) ||
                    text.includes(query);
            } catch (error) {
                console.warn('Error filtering click data:', error);
                return false;
            }
        });
    }

    filteredClicks = filtered;
    updateDisplayedStats();
    renderTable();
    updatePagination();
}

// 更新显示的统计信息
function updateDisplayedStats() {
    displayedClicksEl.textContent = formatNumber(filteredClicks.length);
}

// 渲染表格
function renderTable() {
    if (filteredClicks.length === 0) {
        historyTableBody.innerHTML = '<tr><td colspan="6" class="no-data">No matching records found</td></tr>';
        return;
    }

    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, filteredClicks.length);
    const pageData = filteredClicks.slice(startIndex, endIndex);

    const rows = pageData.map(click => {
        try {
            const time = new Date(click.timestamp);
            const timeStr = time.toLocaleString('en-US', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            });

            const domain = new URL(click.url).hostname;
            const element = escapeHtml(click.element.selector);
            const text = escapeHtml(click.element.text || '');
            const position = `(${click.x}, ${click.y})`;
            const urlLink = `<a href="${escapeHtml(click.url)}" target="_blank" title="${escapeHtml(click.url)}">View Page</a>`;

            return `
                <tr>
                    <td class="time-cell">${timeStr}</td>
                    <td class="domain-cell">${domain}</td>
                    <td class="element-cell" title="${element}">${element}</td>
                    <td class="text-cell" title="${text}">${text}</td>
                    <td class="position-cell">${position}</td>
                    <td class="url-cell">${urlLink}</td>
                </tr>
            `;
        } catch (error) {
            console.warn('Error rendering click record:', error);
            return `
                <tr>
                    <td colspan="6" class="no-data">Data format error</td>
                </tr>
            `;
        }
    }).join('');

    historyTableBody.innerHTML = rows;
}

// 更新分页信息
function updatePagination() {
    const totalPages = Math.ceil(filteredClicks.length / pageSize);
    const startIndex = (currentPage - 1) * pageSize + 1;
    const endIndex = Math.min(currentPage * pageSize, filteredClicks.length);

    pageInfo.textContent = `Showing ${startIndex} - ${endIndex} of ${filteredClicks.length} records`;

    // 更新页码输入框
    pageInput.value = currentPage;
    pageInput.max = totalPages;
    totalPagesSpan.textContent = `/ ${totalPages}`;

    // 更新按钮状态
    prevPageBtn.disabled = currentPage <= 1;
    nextPageBtn.disabled = currentPage >= totalPages;
    goPageBtn.disabled = totalPages <= 1;
}

// 改变页码
function changePage(page) {
    const totalPages = Math.ceil(filteredClicks.length / pageSize);
    if (page < 1 || page > totalPages) return;

    currentPage = page;
    renderTable();
    updatePagination();

    // 滚动到表格顶部
    document.querySelector('.table-container').scrollTop = 0;
}

// 处理搜索
function handleSearch() {
    searchQuery = searchInput.value.trim();
    currentPage = 1;
    applyFilters();
}

// 清除搜索
function clearSearch() {
    searchInput.value = '';
    searchQuery = '';
    currentPage = 1;
    applyFilters();
}

// 导出为 JSON
function exportToJson() {
    try {
        const dataToExport = {
            exportTime: new Date().toISOString(),
            totalRecords: filteredClicks.length,
            filter: currentFilter,
            searchQuery: searchQuery,
            data: filteredClicks
        };

        const blob = new Blob([JSON.stringify(dataToExport, null, 2)], { type: 'application/json' });
        downloadFile(blob, `click_history_${getCurrentDateString()}.json`);
        showSuccess('JSON file exported successfully');
    } catch (error) {
        console.error('Failed to export JSON:', error);
        showError('Failed to export JSON');
    }
}

// 导出为 CSV
function exportToCsv() {
    try {
        const headers = ['Time', 'Domain', 'Element Selector', 'Text Content', 'X Coordinate', 'Y Coordinate', 'Page URL'];
        const csvContent = [
            headers.join(','),
            ...filteredClicks.map(click => {
                const time = new Date(click.timestamp).toLocaleString('en-US');
                const domain = new URL(click.url).hostname;
                const element = `"${click.element.selector.replace(/"/g, '""')}"`;
                const text = `"${(click.element.text || '').replace(/"/g, '""')}"`;
                const url = `"${click.url.replace(/"/g, '""')}"`;

                return [time, domain, element, text, click.x, click.y, url].join(',');
            })
        ].join('\n');

        const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8' });
        downloadFile(blob, `click_history_${getCurrentDateString()}.csv`);
        showSuccess('CSV file exported successfully');
    } catch (error) {
        console.error('Failed to export CSV:', error);
        showError('Failed to export CSV');
    }
}

// 下载文件
function downloadFile(blob, filename) {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// 获取当前日期字符串
function getCurrentDateString() {
    const now = new Date();
    return now.toISOString().split('T')[0];
}

// 格式化数字
function formatNumber(num) {
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
    }
    return num.toString();
}

// 清空所有数据
async function clearAllData() {
    if (!confirm('Are you sure you want to clear all click history data? This action cannot be undone!')) {
        return;
    }

    try {
        clearAllBtn.textContent = 'Clearing...';
        clearAllBtn.disabled = true;

        await chrome.storage.local.clear();
        allClicks = [];
        filteredClicks = [];
        currentPage = 1;

        updateStats(0, 0);
        applyFilters();

        showSuccess('All data has been cleared');

    } catch (error) {
        console.error('Failed to clear data:', error);
        showError('Failed to clear data');
    } finally {
        clearAllBtn.textContent = 'Clear All Data';
        clearAllBtn.disabled = false;
    }
}

// HTML 转义函数
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 显示成功消息
function showSuccess(message) {
    showNotification(message, 'success');
}

// 显示错误消息
function showError(message) {
    showNotification(message, 'error');
}

// 显示通知
function showNotification(message, type) {
    // 移除现有通知
    const existingNotification = document.querySelector('.notification');
    if (existingNotification) {
        existingNotification.remove();
    }

    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 16px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        z-index: 1000;
        animation: slideIn 0.3s ease;
        ${type === 'success' ? 'background: #059669; color: white;' : 'background: #dc2626; color: white;'}
    `;

    // 添加动画样式
    if (!document.getElementById('notification-style')) {
        const style = document.createElement('style');
        style.id = 'notification-style';
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
        `;
        document.head.appendChild(style);
    }

    document.body.appendChild(notification);

    // 自动移除通知
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 3000);
}

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + F：聚焦搜索框
    if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault();
        searchInput.focus();
    }

    // Ctrl/Cmd + R：刷新数据
    if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
        e.preventDefault();
        loadData();
    }

    // 左右箭头键：翻页
    if (e.key === 'ArrowLeft' && !e.target.matches('input')) {
        e.preventDefault();
        changePage(currentPage - 1);
    }

    if (e.key === 'ArrowRight' && !e.target.matches('input')) {
        e.preventDefault();
        changePage(currentPage + 1);
    }
});